import 'dart:io';

import 'package:bboy_music_box_2023/bean/bean_music_info.dart';
import 'package:bboy_music_box_2023/controllers/ctrl_upload.dart';
import 'package:bboy_music_box_2023/network/enum_connect_state.dart';
import 'package:bboy_music_box_2023/res/colors.dart';
import 'package:file_picker/file_picker.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';

class UploadView extends StatefulWidget {

  UploadView({Key? key}) : super(key: key);

  @override
  State<UploadView> createState() => _UploadViewState();
}

class _UploadViewState extends State<UploadView> {
  @override
  Widget build(BuildContext context) {
    return Container(
      padding: const EdgeInsets.all(10.0),
      child: Column(
        children: <Widget>[
          Row(
            children: [
              Expanded(
                child: Container(
                  padding: const EdgeInsets.symmetric(
                    horizontal: 5.0,
                    vertical: 2.0,
                  ),
                  decoration: BoxDecoration(
                    border: Border.all(color: Colors.grey, width: 0.5),
                  ),
                  alignment: Alignment.centerRight,
                  child: Row(
                    children: [
                      Expanded(
                        child: buildFileNameText(),
                      ),
                      MaterialButton(
                        color: Colors.white,
                        onPressed: () async {
                          await pickMusicFile();
                        },
                        child: Container(
                          child: Text('选择文件'),
                        ),
                      ),
                    ],
                  ),
                ),
              ),
            ],
          ),
          Expanded(
            child: buildMusicInfoColumn(),
          )
        ],
      ),
    );
  }

  //构建音乐信息部分
  Widget buildMusicInfoColumn() {
    return Obx(() {
      bool isSelected = UploadCtrl.to.fileNameLive.value.isNotEmpty;
      double progress = UploadCtrl.to.uploadProgress.value;
      return Visibility(
        visible: isSelected,
        child: Column(
          children: [
            SizedBox(height: 15.0),
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Container(
                  child: Text(
                    '音乐名称 ',
                    style: TextStyle(
                      color: Colors.black,
                      fontWeight: FontWeight.w500,
                      fontSize: 14.0,
                    ),
                  ),
                ),
                SizedBox(width: 10.0),
                Expanded(
                  child: Container(
                    child: Obx(() {
                      return Text(
                        UploadCtrl.to.fileNameLive.value,
                        style: TextStyle(
                          color: Colors.black87,
                          fontSize: 12.0,
                        ),
                      );
                    }),
                  ),
                ),
              ],
            ),
            SizedBox(height: 10.0),
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Container(
                  child: Text(
                    '音乐时长 ',
                    style: TextStyle(
                      color: Colors.black,
                      fontWeight: FontWeight.w500,
                      fontSize: 14.0,
                    ),
                  ),
                ),
                SizedBox(width: 10.0),
                Expanded(
                  child: Container(
                    child: Obx(() {
                      int secs = UploadCtrl.to.durationLive.value;
                      return Text(
                        '${(secs ~/ 60).toString().padLeft(2, '0')}'
                        ':${(secs / 60).toInt().toString().padLeft(2, '0')}',
                        style: TextStyle(
                          color: Colors.black87,
                          fontSize: 12.0,
                        ),
                      );
                    }),
                  ),
                ),
              ],
            ),
            SizedBox(height: 10.0),
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Container(
                  child: Text(
                    '音乐路径 ',
                    style: TextStyle(
                      color: Colors.black,
                      fontWeight: FontWeight.w500,
                      fontSize: 14.0,
                    ),
                  ),
                ),
                SizedBox(width: 10.0),
                Expanded(
                  child: Container(
                    child: Obx(() {
                      return Text(
                        UploadCtrl.to.filePathLive.value,
                        style: TextStyle(
                          color: Colors.black87,
                          fontSize: 12.0,
                        ),
                      );
                    }),
                  ),
                ),
              ],
            ),
            SizedBox(height: 10.0),
            Expanded(child: Container()),
            Row(
              mainAxisAlignment: MainAxisAlignment.center,
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Container(
                  child: MaterialButton(
                    padding: const EdgeInsets.symmetric(
                      vertical: 10.0,
                      horizontal: 20.0,
                    ),
                    color: Colors.white,
                    onPressed: uploadMusicFile,
                    child: Container(
                      child: Text(
                        '点击上传',
                        style: TextStyle(
                          color: Colors.black,
                          fontSize: 16.0,
                        ),
                      ),
                    ),
                  ),
                ),
              ],
            ),
            SizedBox(height: 70.0),
          ],
        ),
      );
    });
  }

  void uploadMusicFile() async {
    List<File> files = [];
    File file = UploadCtrl.to.fileLive.value;
    int duration = UploadCtrl.to.durationLive.value;
    String fileName = UploadCtrl.to.fileNameLive.value;
    if (fileName.endsWith(".mp3")) {
      fileName = fileName.replaceAll(".mp3", "");
    }
    if (fileName.endsWith(".MP3")) {
      fileName = fileName.replaceAll(".MP3", "");
    }
    files.add(UploadCtrl.to.fileLive.value);
    List<MusicInfo> musicInfos = [];
    musicInfos.add(MusicInfo.fromParams(
        duration: duration,
        name: fileName,
        desc: "APP Desc",
        uploader: "Bboy AKai"));
    MusicInfoListBean musicInfoListBean =
        new MusicInfoListBean.fromParams(list: musicInfos);
    UploadCtrl.to.uploadProgress.value = 0;
    UploadCtrl.to.uploadProgress.refresh();
    UploadCtrl.to.uploadMusicFile(files, musicInfoListBean);
    showLoadingDialog();
  }

  void showLoadingDialog() {
    Get.dialog(
      PopScope(
        canPop: false,
        child: Center(
          child: Material(
            color: Colors.transparent,
            child: Container(
              padding:
                  const EdgeInsets.symmetric(horizontal: 10.0, vertical: 20.0),
              width: Get.width * 5 / 6,
              height: Get.height / 4,
              decoration: BoxDecoration(
                borderRadius: BorderRadius.circular(4.0),
                color: Colors.white,
              ),
              child: Obx(() {
                double progress = UploadCtrl.to.uploadProgress.value;
                ConnectState state = UploadCtrl.to.uploadState.value;

                return Column(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    Expanded(
                      child: Column(
                        mainAxisAlignment: MainAxisAlignment.center,
                        children: [
                          Visibility(
                            visible: state.isWaiting,
                            child: Container(
                              child: Text(
                                '上传中，请稍等',
                                style: TextStyle(
                                  fontSize: 20.0,
                                  fontWeight: FontWeight.bold,
                                ),
                              ),
                            ),
                          ),
                          Visibility(
                            visible: state.isErr,
                            child: Container(
                              child: Text(
                                '上传失败。',
                                style: TextStyle(
                                  color: Colors.redAccent,
                                  fontSize: 20.0,
                                  fontWeight: FontWeight.bold,
                                ),
                              ),
                            ),
                          ),
                          Visibility(
                            visible: state.isDone,
                            child: Container(
                              child: Text(
                                '上传完成。',
                                style: TextStyle(
                                  color: Colors.black,
                                  fontSize: 20.0,
                                  fontWeight: FontWeight.bold,
                                ),
                              ),
                            ),
                          ),
                          SizedBox(height: 10.0),
                          Visibility(
                            visible: state.isWaiting,
                            child: Row(
                              crossAxisAlignment: CrossAxisAlignment.center,
                              mainAxisAlignment: MainAxisAlignment.center,
                              children: [
                                SizedBox(width: 10.0),
                                Container(
                                  child: Text(
                                    '${(progress * 100).toInt()}%',
                                    style: TextStyle(
                                      color: Colors.black,
                                      fontSize: 8.0,
                                    ),
                                  ),
                                ),
                                SizedBox(width: 5.0),
                                Expanded(
                                  child: Center(
                                    child: LinearProgressIndicator(
                                      backgroundColor: Colors.grey,
                                      valueColor: const AlwaysStoppedAnimation(
                                          Colors.black),
                                      value: progress,
                                    ),
                                  ),
                                ),
                                SizedBox(width: 10.0),
                              ],
                            ),
                          ),
                        ],
                      ),
                    ),
                    Visibility(
                      visible: !state.isWaiting,
                      child: InkWell(
                        onTap: () {
                          Get.back();
                        },
                        child: Container(
                          margin: const EdgeInsets.only(top: 20.0),
                          child: Row(
                            mainAxisAlignment: MainAxisAlignment.center,
                            children: [
                              Container(
                                padding: const EdgeInsets.symmetric(
                                    vertical: 5.0, horizontal: 10.0),
                                child: Text(
                                  '确定',
                                  style: TextStyle(
                                    color: Colors.black,
                                    fontSize: 18.0,
                                  ),
                                ),
                                decoration: BoxDecoration(
                                  border: Border.all(
                                      color: Colors.grey, width: 0.4),
                                ),
                              ),
                            ],
                          ),
                        ),
                      ),
                    ),
                  ],
                );
              }),
            ),
          ),
        ),
      ),
      barrierDismissible: false,
    );
  }

  Widget buildFileNameText() {
    return Obx(
      () {
        return Container(
          padding: const EdgeInsets.all(5.0),
          child: Text(
            UploadCtrl.to.fileNameLive.value,
            style: TextStyle(
              color: Colors.black,
              fontSize: 14.0,
            ),
          ),
        );
      },
    );
  }

  Future<void> pickMusicFile() async {
    FilePickerResult? result = await FilePicker.platform.pickFiles(
      type: FileType.custom,
      allowedExtensions: ['mp3'],
    );
    if (result != null) {
      var single = result.files.single;
      String fileName = single.name;

      File file = File(result.files.single.path!);
      String path = file.path;

      UploadCtrl.to.fileLive.value = file;
      UploadCtrl.to.fileNameLive.value = fileName;
      UploadCtrl.to.filePathLive.value = path;
      UploadCtrl.to.refresh();

      UploadCtrl.to.loadMusic(file);
    } else {
      // User canceled the picker
    }
  }
}
